# -*- coding: utf-8 -*-
"""
BIG Downloader Toolbox Plugin - FIXED VERSION WITH CORRECT ICONS
"""

from qgis.core import QgsApplication, QgsMessageLog, Qgis
from qgis.PyQt.QtWidgets import QAction, QMenu, QMessageBox
from qgis.PyQt.QtGui import QIcon
from qgis import processing
import os

class BIGDownloaderToolboxPlugin:
    """Main plugin class - FIXED VERSION"""
    
    def __init__(self, iface):
        self.iface = iface
        self.provider = None
        self.menu = None
        self.toolbar = None
        self.actions = []
        self.plugin_dir = os.path.dirname(__file__)

    def initGui(self):
        """Initialize GUI - FIXED"""
        try:
            # Import provider
            from .big_downloader_toolbox_provider import BIGDownloaderToolboxProvider
            
            # Register provider
            self.provider = BIGDownloaderToolboxProvider()
            QgsApplication.processingRegistry().addProvider(self.provider)
            
            QgsMessageLog.logMessage(
                'BIG Downloader Provider registered successfully',
                'BIG Downloader',
                Qgis.Info
            )
            
            # Create menu and toolbar
            self.create_menu()
            self.create_toolbar()
            
            QgsMessageLog.logMessage(
                'BIG Downloader Toolbox plugin loaded successfully',
                'BIG Downloader',
                Qgis.Info
            )
            
        except Exception as e:
            QgsMessageLog.logMessage(
                f'Error initializing plugin: {str(e)}',
                'BIG Downloader',
                Qgis.Critical
            )
            import traceback
            QgsMessageLog.logMessage(
                traceback.format_exc(),
                'BIG Downloader',
                Qgis.Critical
            )

    def get_icon_path(self, icon_name):
        """Get correct icon path"""
        # Coba cari di folder images
        images_dir = os.path.join(self.plugin_dir, 'images')
        icon_path = os.path.join(images_dir, icon_name)
        
        if os.path.exists(icon_path):
            return icon_path
        
        # Fallback ke icon utama
        return os.path.join(self.plugin_dir, 'icon.png')

    def create_menu(self):
        """Create menu with correct icons"""
        # Main menu
        self.menu = QMenu("BIG Downloader Toolbox")
        self.menu.setIcon(QIcon(self.get_icon_path('icon_login.png')))
        
        # Tool 1: Login INA-Geoportal
        action_login = QAction(
            QIcon(self.get_icon_path('icon_login.png')),
            "1. Login INA-Geoportal",
            self.iface.mainWindow()
        )
        action_login.setToolTip("Buka halaman login INA-Geoportal untuk ambil Token")
        action_login.triggered.connect(lambda: self.run_algorithm('login_demnas'))
        self.menu.addAction(action_login)
        self.actions.append(action_login)
        
        # Tool 2: Download DEMNAS
        action_demnas = QAction(
            QIcon(self.get_icon_path('icon_demnas.png')),
            "2. Download DEMNAS (Mosaic)",
            self.iface.mainWindow()
        )
        action_demnas.setToolTip("Download dan Mosaic data DEMNAS")
        action_demnas.triggered.connect(lambda: self.run_algorithm('download_demnas_pro'))
        self.menu.addAction(action_demnas)
        self.actions.append(action_demnas)
        
        # Tool 3: Download RBI
        action_rbi = QAction(
            QIcon(self.get_icon_path('icon_rbi.png')),
            "3. Download RBI",
            self.iface.mainWindow()
        )
        action_rbi.setToolTip("Download Peta Rupa Bumi Indonesia (RBI)")
        action_rbi.triggered.connect(lambda: self.run_algorithm('download_rbi_tool_pro'))
        self.menu.addAction(action_rbi)
        self.actions.append(action_rbi)
        
        # Tool 4: Download BATNAS
        action_batnas = QAction(
            QIcon(self.get_icon_path('icon_batnas.png')),
            "4. Download BATNAS",
            self.iface.mainWindow()
        )
        action_batnas.setToolTip("Download Data Batimetri Nasional (BATNAS)")
        action_batnas.triggered.connect(lambda: self.run_algorithm('download_batnas'))
        self.menu.addAction(action_batnas)
        self.actions.append(action_batnas)
        
        # Separator
        self.menu.addSeparator()
        
        # About
        action_about = QAction(
            QIcon(self.get_icon_path('icon_login.png')),
            "About",
            self.iface.mainWindow()
        )
        action_about.triggered.connect(self.show_about)
        self.menu.addAction(action_about)
        
        # Add menu to plugin menu
        self.iface.pluginMenu().addMenu(self.menu)

    def create_toolbar(self):
        """Create toolbar with icons"""
        self.toolbar = self.iface.addToolBar("BIG Downloader Toolbox")
        self.toolbar.setObjectName("BIGDownloaderToolbox")
        
        # Add actions to toolbar
        for action in self.actions:
            self.toolbar.addAction(action)

    def run_algorithm(self, algorithm_name):
        """Run processing algorithm"""
        try:
            algorithm_id = f'big_downloader_toolbox:{algorithm_name}'
            processing.execAlgorithmDialog(algorithm_id)
        except Exception as e:
            self.iface.messageBar().pushCritical(
                "Error", 
                f"Failed to run {algorithm_name}: {str(e)}"
            )

    def unload(self):
        """Unload plugin"""
        if self.provider:
            QgsApplication.processingRegistry().removeProvider(self.provider)
        
        # Remove menu
        if self.menu:
            self.iface.pluginMenu().removeAction(self.menu.menuAction())
        
        # Remove toolbar
        if self.toolbar:
            self.toolbar.clear()
            self.iface.mainWindow().removeToolBar(self.toolbar)
            self.toolbar.deleteLater()
        
        # Clear references
        self.actions = []

    def show_about(self):
        """Show about dialog"""
        QMessageBox.information(
            self.iface.mainWindow(),
            "About BIG Downloader Toolbox",
            "<h3>BIG Downloader Toolbox</h3>"
            "<p>Plugin untuk mengunduh data BIG (Badan Informasi Geospasial):</p>"
            "<ul>"
            "<li><b>DEMNAS</b> - Digital Elevation Model Nasional</li>"
            "<li><b>RBI</b> - Rupabumi Indonesia</li>"
            "<li><b>BATNAS</b> - Batimetri Nasional</li>"
            "</ul>"
            "<p><b>Versi:</b> 1.0</p>"
            "<p><b>Sumber Data:</b> <a href='https://tanahair.indonesia.go.id'>INA-Geoportal</a></p>"
            "<p><b>Catatan:</b> Diperlukan token API dari INA-Geoportal (gunakan Tool #1)</p>"
        )